<template>
  <basic-container>
    <!-- 头部搜索栏 -->
    <div class="search-wrap">
      <div class="merchant" style="display: inline-block">
        选择商家：
        <el-select
          filterable
          remote
          :remote-method="remoteMerchant"
          v-model="merchantId"
          @change="changeMerchant"
          placeholder="请选择">
          <el-option
            v-for="(item,index) in merchantList"
            :key="index"
            :label="item.merchantName"
            @change="changeMerchant"
            :value="item.merchantId"/>
        </el-select>
      </div>
      <div class="shop" style="display: inline-block">
        选择店铺：
        <el-select
          filterable
          remote
          :remote-method="remoteShop"
          v-model="shopId"
          @change="changeShop"
          placeholder="请选择">
          <el-option
            v-for="(item,index) in shopList"
            :key="index"
            :label="item.name"
            @change="changeShop"
            :value="item.shopId"/>
        </el-select>
      </div>
      <div class="platform-shop"style="display: inline-block">
        平台售卖店铺：
        <el-select filterable
                   v-model="platformShopId"
                   placeholder="请选择需同步平台店铺"
        >
          <el-option
            v-for="(item,index) in platformShopList"
            :key="index"
            :label="item.name"
            :value="item.shopId"
          />
        </el-select>
      </div>
      <div style="padding-left: 20px;">
        <el-input v-model="searchText" placeholder="请输入内容" width="286">
          <el-select slot="prepend" v-model="searchSelect" placeholder="请选择" class="search">
            <el-option label="商品编号" value="1"></el-option>
            <el-option label="商品名称" value="2"></el-option>
          </el-select>
        </el-input>
        <el-select slot="prepend" v-model="modelStatus" style="margin-left: 10px; width: 120px;" placeholder="规格">
          <el-option label="全部规格" value=""></el-option>
          <el-option label="多规格" value="1"></el-option>
          <el-option label="单规格" value="0"></el-option>
        </el-select>
        <el-button type="primary" size="small" class="search-btn" @click="searchGoodsList">搜索</el-button>
        <el-button type="default" size="small" @click="resetGoodsList">清除条件</el-button>
        <div class="tool-btns">
          <el-button type="primary" @click="ToAddGoods">新增商品</el-button>
        </div>
        <div class="productInformation">
          <goods_import ref="goodsImport" :inputShopId="shopId"/>
        </div>
      </div>

    </div>
    <!-- tab选项卡 -->
    <avue-tabs :option="taboption" @change="handleChange" style="padding-top: 0;"></avue-tabs>
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="220px" class="aside-nav">
        <avue-tree
          :option="option"
          :data="goodsCategories"
          @node-click="getCategoryGoods"
        >
        </avue-tree>
      </el-aside>
      <!-- 表格区域 -->
      <el-main>
        <avue-crud ref="crud" :data="tableData" :option="tableoption" @row-del="rowDel">

          <template slot="thumbUrl" slot-scope="scope">
            <img width="60px" height="60px" :src="scope.row.thumbUrl" />
          </template>

          <template slot-scope="scope" slot="sort">
            <input-box :changeValue="scope.row.sort"
                       :goodsName="scope.row.goodsName"
                       :goods-id="scope.row.goodsId"
                       :type="1"
                       title="修改权重值"
                       @refresh="refresh"
            ></input-box>
          </template>

          <template slot-scope="scope" slot="storage">
            <input-box :changeValue="scope.row.storage"
                       :goodsName="scope.row.goodsName"
                       :goods-id="scope.row.goodsId"
                       :type="2"
                       title="修改库存"
                       @refresh="refresh"
            ></input-box>
          </template>

          <template slot-scope="scope" slot="isMarketable">
            <el-switch
              v-model="scope.row.isMarketable"
              :disabled="marketObj[scope.row.goodsId]"
              :active-value= '1'
              :inactive-value= '0'
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="marketTable(scope.row)"
            >
            </el-switch>
          </template>
          <!--   是否平台售卖       -->
          <template slot-scope="scope" slot="relationType">
            <el-switch
              v-model="scope.row.relationType"
              :disabled="relationObj[scope.row.goodsId]"
              active-value="1"
              inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="isRelationType(scope.row)"
            >
            </el-switch>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text" icon="el-icon-edit" @click="jumpToEidt(scope.row)">编辑</el-button>
            <el-button type="text" @click="jumpToDetail(scope.row)">详情</el-button>
          </template>
        </avue-crud>
      </el-main>
    </el-container>
    <el-footer>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="currentPage" :page-sizes="[10, 20, 40, 60]" :page-size="10"
                     background :layout="layout" :total="totalCount" class="pagination">
      </el-pagination>
    </el-footer>
  </basic-container>
</template>

<script>
  import {taboption, tableoption} from '../../const/crud/supply/supplygoodsoption'
  import {fetchList} from "../../api/manage/shop";
  import {getmerchantList} from "../../api/supply/supplier"
  import {getGoodsList, putPlatformSales, cancelPlatformSales, delGoods, isMarketTable} from "../../api/supply/suppliergoods"
  import {getCategoryTree} from "../../api/goods/goodscategory"
  import inputBox from "./component/inputBox";
  import goods_import from "@/components/goods/excel_import/goods_import";
  import {getStore} from "../../util/store";

  export default {
    components: {
      inputBox,
      goods_import
    },
    data() {
      return {
        type: {},
        // tab栏配置
        taboption: taboption,
        // 表格配置
        tableoption: tableoption,
        // request: new request(),
        // 表格数据
        tableData: [],
        // 搜索框文本
        searchText: '',
        // 搜索选择框
        searchSelect: '2',
        // 规格
        modelStatus: '',
        //选择供应商
        merchantId: '',
        //店铺Id
        shopId: '',
        totalCount: 10,
        // 当前页
        currentPage: 1,
        pageSize: 10,
        layout: "total, sizes, prev, pager, next, jumper",
        categoryId: '',
        // request数据
        goodsCategories: [],
        activeTab: '0',
        // 供应商列表
        merchantList: [],
        // 店铺列表
        shopList: [],
        toShopId: '',
        toMerchantId: '',
        option: {
          defaultExpandAll:true,
          addBtn: false,
          props:{
            label: 'name',
            value: 'id',
            children: 'children'
          }
        },
        marketObj: {},
        relationObj:{},
      //  平台店铺Id
        platformShopId: '',
        platformShopList: []
      }
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        if(vm.$route.query.res) {
          vm.toShopId = vm.$route.query.res.shopId;
          vm.toMerchantId = vm.$route.query.res.merchantId
        }
        vm.getHeight()
      });
    },
    created() {
      this.getmerchantList({status: 2})
      this.pmId = getStore({name: "pmId"});
      this.getFetchList()
    },
    methods: {
      //表格高度
      getHeight() {
        let tableHeight = Math.max(window.innerHeight - 400, 300);
        this.tableoption.maxHeight = tableHeight + 'px';

      },
      //获取平台店铺
      getFetchList() {
        let params = {
          current: 1,
          size: 100,
          merchantId: this.pmId,
          status: this.useStatus
        }
        fetchList(params).then(res => {
          this.platformShopList = res.data.data.records
          this.platformShopId = this.platformShopList[0].shopId
        })
      },
      // 获取表格数据
      getTableData(params = {}) {
        this.marketObj = {}
        this.relationObj = {}
        let goodsStatus = ''
        if (this.activeTab === '0') {
          goodsStatus = ""
        }
        if (this.activeTab === '1') {
          goodsStatus = 0
        }
        if (this.activeTab === '2') {
          goodsStatus = 2
        }
        if (this.activeTab === '3') {
          goodsStatus = 1
        }
        params.goodsStatus = goodsStatus
        params.shopId = this.shopId
        params.current = this.currentPage
        params.size = params.pageSize || this.pageSize
        params.categoryId = this.categoryId
        getGoodsList(params).then(res => {
          this.totalCount = res.data.data.total
          this.tableData = res.data.data.records
        })
      },
      // 搜索
      searchGoodsList() {
        const params = {modelStatus: this.modelStatus, currentPage: this.currentPage}
        if (this.searchSelect === '1') params.goodsSn = this.searchText
        if (this.searchSelect === '2') params.goodsName = this.searchText
        this.getTableData(params)
      },
      // 清除搜索框
      resetGoodsList() {
        this.loading = true
        this.categoryId = ''
        this.searchText = ''
        this.modelStatus = ''
        this.searchSelect = '1'
        this.currentPage = 1
        const params = {}
        params.pageNo = this.currentPage
        const menu = this.$refs.goodsCategoryMenu
        this.getTableData(params)
      },
      // tab栏
      handleChange(column) {
        console.log(column);
        this.activeTab = column.prop
        const params = {}
        if (this.searchSelect === '1') {
          params.goodsSn = this.searchText
        }
        if (this.searchSelect === '2') {
          params.goodsName = this.searchText
        }
        params.pageNo = this.currentPage
        if (this.shopId) {
          this.getTableData(params)
        }
      },
      // 获取分类商品
      getCategoryGoods(categoryId) {
        console.log(categoryId);
        const params = {}
        params.pageNo = this.currentPage
        this.categoryId = categoryId.id
        this.getTableData(params)
      },
      // 获取商品分类列表
      getGoodsCategoryList(param = {}) {
        getCategoryTree({shopId: this.shopId,allShow: true}).then(res => {
          // console.log(res.data.data);
          this.goodsCategories = res.data.data
        })
      },
      // 获取供应商的商家列表
      getmerchantList(param = {}) {
        getmerchantList(param).then(res => {
          // console.log(res);
          let merchantList = []
          res.data.data.records.forEach(item => {
            // console.log(item.pdsType);
            if(item.pdsType == 0) {
              merchantList.push(item)
            }
          })
          this.merchantList = merchantList
          this.merchantId = this.toMerchantId || merchantList[0].merchantId
          this.getShopList()
        })
      },
      remoteMerchant(name = null) {
        let query = {
          merchantName: name,
          status: 2
        };
        getmerchantList(query).then(res => {
          this.merchantList = res.data.data.records;
        });
      },
      //改变merchantId
      changeMerchant() {
        this.categoryId = ''
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          status: 2,
          merchantId: this.merchantId,
          name: name
        }
        fetchList(params).then(res => {
          if (res.data.data.records.length == 0) {
            this.$message.warning("没有店铺")
            this.shopId = ''
            this.tableData = []
            this.goodsCategories = []
          }
          this.shopList = res.data.data.records
          setTimeout(() => {
            this.shopId = this.shopList[0].shopId
            this.getTableData()
            this.getGoodsCategoryList()
          },100)

        })
      },
      //改变shopID
      changeShop() {
        this.categoryId = ''
        this.getTableData()
        this.getGoodsCategoryList()
      },
      //获取商铺列表
      remoteShop(name = null) {
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          status: 2,
          merchantId: this.merchantId,
          name: name
        }
        fetchList(params).then(res => {
          this.shopList = res.data.data.records
        })
      },
      getShopList() {
        let params = {}
        params.current = this.currentPage
        params.size = this.pageSize
        params.status = 2
        params.merchantId = this.merchantId
        fetchList(params).then(res => {
          this.shopList = res.data.data.records
          console.log(this.shopList);
          this.shopId = this.toShopId || res.data.data.records[0].shopId
          getCategoryTree({shopId: res.data.data.records[0].shopId,allShow: true}).then(res => {
            this.goodsCategories = res.data.data
          })
          this.getTableData()
        })
      },
      //分页——跳转页
      handleSizeChange(size) {
        this.pageSize = size
        this.getTableData()
      },
      handleCurrentChange(page) {
        this.currentPage = page
        this.getTableData()
      },
      // 新增商品
      ToAddGoods() {
        if(this.shopId == '' || this.shopId == null) {
          this.$message.error("店铺不能为空")
        }else {
          const query = {
            res: {
              shopId: this.shopId
            }
          }
          this.$router.push({path: 'addsupplygoods', query: query})
        }
      },
      // 编辑商品
      jumpToEidt(row) {
        const query = {
          res: {
            goodsSn: row.goodsSn,
            shopId: this.shopId
          }
        }
        this.$router.push({path: 'editsupplygoods', query: query})
      },
      // 详情商品
      jumpToDetail(row) {
        console.log(row);
        const query = {
          res: {
            goodsId: row.goodsId,
            shopId: row.shopId
          }
        }
        // console.log(query);
        this.$router.push({path: 'detailsupplygoods', query: query})
      },
      //是否上下架
      marketTable(val) {
        let marketable = "";
        this.$set(this.marketObj,val.goodsId,true)
        if (val.isMarketable == "1") {
          marketable = true;
        } else {
          marketable = false;
        }
        let params = {
          goodsId: val.goodsId,
          marketable: marketable
        };
        isMarketTable(params).then(res => {
          let _this = this
          if (val.isMarketable == "1") {
            this.$message.success("上架成功");
            setTimeout(function() {
              _this.$set(_this.marketObj,val.goodsId,false)
            }, 1000);
          }
          if (val.isMarketable == "0") {
            this.$message.success("下架成功");
            setTimeout(function() {
              _this.$set(_this.marketObj,val.goodsId,false)
            }, 1000);
          }

        });
      },
      //是否平台售卖
      isRelationType(val) {
        // console.log(val.relationType);
        this.$set(this.relationObj,val.goodsId,true)
        let params = {}
        params.shopId = val.shopId
        params.supplyGoodsId = val.goodsId
        if (val.relationType == "1") {
          params.platformShopId = this.platformShopId
          putPlatformSales(params).then(res => {
            console.log("上架");
            this.$message.success("关联平台商品成功")
            const _this = this
            setTimeout(function() {
              _this.$set(_this.relationObj,val.goodsId,false)
            }, 1000);
          }).catch(err => {
            val.relationType = "0"
            const _this = this
            setTimeout(function() {
              _this.$set(_this.relationObj,val.goodsId,false)
            }, 1000);
          })
        }
        if (val.relationType == "0") {
          cancelPlatformSales(params).then(res => {
            this.$message.success("取消关联平台商品成功")
            const _this = this
            setTimeout(function() {
              _this.$set(_this.relationObj,val.goodsId,false)
            }, 1000);
            console.log("下架");
          })
        }
      },
      rowDel(row) {
        const goodsId = row.goodsId
        delGoods(goodsId).then(res => {
          this.$message.success("删除商品成功")
          this.getTableData()
        })
      },
      refresh() {
        this.getTableData()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .table {
    width: 100%;
    position: relative;
  }

  .search {
    font-size: 13px;
    width: 100px;
  }

  .tool-btns {
    /*float: right;*/
    margin-left: 30px;
    display: inline-block;
  }

  .productInformation {
    display: inline-block;
    height: 34px;
    display: inline-block;
    margin-left: 30px;

  }
  .search-wrap {
    text-align: left;
    position: relative;
    /*height: 70px;*/
    line-height: 70px;
    padding-left: 10px;
    /*display: flex;*/
  }

  .search-btn {
    margin-left: 20px;
  }

  /* 覆盖框架原生样式 */
</style>
<style>
  .search-wrap .el-select .el-input {
    width: 105px;
  }

  .search-wrap .el-input-group__prepend {
    background-color: #fff;
  }

  .search-wrap .el-input-group {
    width: 25%;
  }

  .search-category {
    font-size: 12px;
    width: 80px;
  }

  .aside-nav {
    height: calc(100vh - 400px);
    text-align: left;
  }

  .merchant {
    margin-left: 20px;
  }

  .shop {
    margin: 0 20px 0 20px;
  }

  .pagination {
    text-align: center;
  }
</style>
